package com.onemileshop.app;

import java.util.ArrayList;
import java.util.List;

import com.onemileshop.entiy.PubConst;
import com.onemileshop.entiy.Session;
import com.onemileshop.entiy.UrlParams;
import com.onemileshop.entiy.model.EMsgHead;
import com.onemileshop.entiy.model.EPostData;
import com.onemileshop.entiy.model.EPostResult;
import com.onemileshop.entiy.model.EShopInfo;
import com.onemileshop.net.NetLogin;
import com.onemileshop.updater.AppUpdater;
import com.onemileshop.utils.UtiDialogsFactory;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class UILogin extends Activity
{
   private Button btnLogin;
   private EditText edtUser;
   private EditText edtPwd;
   private CheckBox cbkShowPwd;
   private CheckBox cbkRemember;

   private void InitControls()
   {
	  btnLogin = (Button) findViewById(R.id.btn_login);
	  edtUser = (EditText) findViewById(R.id.edtUser_login);
	  edtPwd = (EditText) findViewById(R.id.edtPwd_login);
	  cbkShowPwd = (CheckBox) findViewById(R.id.ckbShowPwd_login);
	  cbkRemember = (CheckBox) findViewById(R.id.ckbRemember_login);
   }

   private void InitControlsEvent()
   {
	  btnLogin.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			try
			{
			   if (edtUser == null || edtUser.getText().toString().trim().equals(""))
			   {
				  Toast.makeText(UILogin.this, "请输入用户名", 500).show();
			   }
			   else
			   {
				  final String userName = edtUser.getText().toString().trim();
				  final String userPwd = edtPwd.getText().toString().trim();

				  UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UILogin.this, "正在验证。。。");

				  NetLogin netLogin = new NetLogin(new EMsgHead(UrlParams.Shop_Login.APICode), new NetLogin.ITaskCallBack()
				  {
					 @Override
					 public void DoWhenComplete(EPostResult result)
					 {
						UtiDialogsFactory.getInstance().DismissLoadingDialog();
						if (result != null)
						{
						   if (result.getRspCode().equals("00000000"))
						   {

							  Session.getInstance().setUserName(userName);
							  Session.getInstance().setUserKey(userPwd);
							  Session.getInstance().setShopInfo((EShopInfo) result.getResult());

							  // 登录成功后更新上次登录用户名
							  SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
							  editor.putString(PubConst.Setting.LastUserName, userName);
							  editor.commit();

							  Intent intent = new Intent();
							  intent.setClass(UILogin.this, UIMain.class);
							  startActivity(intent);
							  finish();
						   }
						   else
						   {
							  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UILogin.this, "提示", result.getRspMsg());
						   }
						}
						else
						{
						   UtiDialogsFactory.getInstance().ShowOKAlertDialog(UILogin.this, "提示", "用户名密码错误或网络不通！");
						}
					 }
				  });

				  ArrayList<EPostData> list = new ArrayList<EPostData>();
				  list.add(new EPostData(UrlParams.Shop_Login.LoginName, userName));
				  list.add(new EPostData(UrlParams.Shop_Login.Pwd, userPwd));
				  netLogin.execute(list);
			   }
			}
			catch (Exception e)
			{
			   Log.e(PubConst.Tag.ERROR, "", e);
			   UtiDialogsFactory.getInstance().ShowOKAlertDialog(UILogin.this, "提示", "用户名密码错误或网络不通！");
			}
		 }
	  });

	  cbkShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener()
	  {
		 @Override
		 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
		 {
			if (isChecked)
			{
			   // edtUserKey.setInputType(0x90);//密码可见
			   edtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			}
			else
			{
			   // edtUserKey.setInputType(0x81);//密码不可见
			   edtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
			}
		 }
	  });
   }

   /*
    * (non-Javadoc)
    * 
    * @see android.app.Activity#onCreate(android.os.Bundle)
    */
   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.ui_login);
	  try
	  {
		 if (Session.getInstance().isLogin())
		 {
			Intent intent = new Intent();
			intent.setClass(UILogin.this, UIMain.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		 }
		 InitControls();
		 InitControlsEvent();

		 SharedPreferences userSetting = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE);
		 Boolean isRemember = userSetting.getBoolean(PubConst.Setting.IS_REMEMBER, false);

		 if (isRemember)
		 {
			String lastUserName = userSetting.getString(PubConst.Setting.LastUserName, "");
			cbkRemember.setChecked(true);
			edtUser.setText(lastUserName);
			if (!lastUserName.equals(""))
			{
			   edtPwd.setFocusable(true);
			   edtPwd.requestFocus();
			}
		 }

		 AppUpdater updater = new AppUpdater(this);
		 updater.UpdateApp();
	  }
	  catch (Exception e)
	  {
		 Log.e(PubConst.Tag.ERROR, "", e);
	  }

   }

   @Override
   protected void onDestroy()
   {
	  // 保存上一次用过的用户名
	  try
	  {
		 SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
		 if (cbkRemember.isChecked())
		 {
			editor.putBoolean(PubConst.Setting.IS_REMEMBER, true);
		 }
		 else
		 {
			editor.putBoolean(PubConst.Setting.IS_REMEMBER, false);
		 }
		 editor.putString(PubConst.Setting.LastUserName, edtUser.getText().toString().trim());
		 editor.commit();
	  }
	  catch (Exception e)
	  {
		 Log.e(PubConst.Tag.ERROR, "onDestroy()", e);
	  }

	  super.onDestroy();
   }

   // 退出提示框
   private void FinishDialog()
   {
	  DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
	  {
		 @Override
		 public void onClick(DialogInterface dialog, int which)
		 {
			dialog.dismiss();
			android.os.Process.killProcess(android.os.Process.myPid());
			finish();
		 }
	  };
	  UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UILogin.this, "提示", "您打算退出程序吗？", listener);
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
	  {
		 FinishDialog();
	  }
	  else if (keyCode == KeyEvent.KEYCODE_ENTER)
	  {
		 if (edtUser.isFocused())
		 {
			edtPwd.setFocusable(true);
			edtPwd.requestFocus();
			edtPwd.setFocusableInTouchMode(true);
		 }
	  }
	  return true;
   }
}
